import 'package:common_utils/common_utils.dart';
import 'package:flutter_neumorphic_plus/flutter_neumorphic.dart';
import 'package:get/get.dart';
import 'package:psi/base/base_controller.dart';
import 'package:psi/entity/common_resp.dart';
import 'package:psi/entity/purchass_entity.dart';
import 'package:psi/entity/response/purchase_item_resp.dart';
import 'package:psi/entity/response/recent_names_list_resp.dart';
import 'package:psi/http/api_service.dart';

import 'purchase_add_state.dart';

class PurchaseAddLogic extends BaseController {
  final PurchaseAddState state = PurchaseAddState();

  @override
  void onReady() async {
    // TODO: implement onReady
    super.onReady();

    if (Get.arguments["type"] != null) {
      state.type = Get.arguments["type"];
      if (state.type == PurchaseType.add) {
        state.isEdit.value = true;
      }
    }
    if (Get.arguments["data"] != null) {
      state.purchase.value = Get.arguments["data"];
    }
    update(["all"]);
    await getRecentNames();

  }

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
  }

  void addAction() {
    state.purchase.value.itemList!.add(PurchaseItem());
    update(["item"]);
  }

  void deleteAction(PurchaseItem item) {
    state.purchase.value.itemList!.remove(item);
    update(["item", "amount"]);
  }

  Future<void> getRecentNames({int? count}) async {
      try {
        if (count != null) {
          state.count.value = count;
        }
        RecentNamesListResp resp = await ApiService.request.recentNames(count: state.count.value);
        if (resp.code == 0) {
          state.recentNames.value = resp.data ?? [];
          update(["itemRecentNames"]);
        }
      } catch(e) {
        LogUtil.e(e);
      }
  }

  Future<void> clickAction() async {

    if (state.type == PurchaseType.add) {
      await doneAction();
    } else {
      if (state.isEdit.value) {
        await updateAction();
      }
    }

  }

  Future<void> updateAction() async {
    showLoading();
    try {
      PurchaseItemResp resp = await ApiService.request.editPurchase(state.purchase.value);
      hideLoading();
      if (resp.code == 0) {
        state.isEdit.value = !state.isEdit.value;
        goBack(result: resp.data);
      } else {
        showToast(resp.message);
      }
    } catch(e) {
      hideLoading();
      showToast("服务器连接失败，请稍后再试");
    }
  }

  Future<void> doneAction() async {
    try {
      showLoading();
      PurchaseItemResp resp = await ApiService.request.addPurchase(state.purchase.value);
      hideLoading();
      if (resp.code == 0) {
        goBack(result: resp.data);
      } else {
        showToast(resp.message);
      }
    } catch(e) {
      hideLoading();
      showToast("服务器连接失败，请稍后再试");
      LogUtil.e(e);
    }
  }
}
